﻿(function () {
    'use strict';
    var blogType = 0; //微博数据来源类型
    angular.module('infinite-scroll').value('THROTTLE_MILLISECONDS', 1000)
    var blogModule = angular.module("BlogModule", ['elif', 'blogService', 'commonApp', 'blogDirectiveModule']);
    blogModule.controller("MicroBlogCtrl", function ($scope, $timeout, $rootScope, $http, microblogsService) {
            $scope.userId = $('.weibo_detail_wrap').attr('uid'); //当前用户的id
            $scope.accountRole = $('.weibo_detail_wrap').attr('role'); //当前用户的
            $scope.Pager = {
                startId: 0,
                pageIndex: 0, //页码
                itemList: [], //列表项
                TotalPages: 0 //总共多少页
            }
            $scope.BlogContent = '';
            $scope.isOpen = false;
            $scope.busy = false;

            /**
             * 发布微博内容输入检测事件
             * @returns {} 
             */
            $scope.BlogContentInput = function () {
                if ($scope.BlogContent.length > 140) {
                    $scope.BlogContent = $scope.BlogContent.slice(0, 140);
                }
                //动态【剩余文字字数】的位置
                var blogText = $("#blog_txt");
                if ($(blogText).prop("scrollHeight") > $(blogText).height()) {
                    $(".txtnum_box").css('right', '26px');
                } else {
                    $(".txtnum_box").css('right', '12px');
                }
            }

            /**
             * 关键字搜索
             * @param {} $event 
             * @returns {} 
             */
            $rootScope.search = function ($event) {
                if (($event && $event.which === 13) || !$event) {
                    var wd = $rootScope.searchWord;
                    if (!wd) {
                        msg("请输入要搜索的关键字！", 2);
                        return;
                    }
                    window.location.href = '/Social/Blog/blogsearch#/synthesis?search=' + encodeURI(wd);
                }

            }

            /**
             * 获取微博列表数据
             * @returns {} 
             */
            $scope.goMicroBlogs = function () {
                blogType = $('.weibo_wrap').attr('blog-type');
                $scope.blogType = blogType;
                var res = $scope.initPending();
                if (!res) return;
                if (blogType == 6) {
                    $scope.getTraderBlogList();
                } else {
                    microblogsService.getBlogs(parseInt(blogType),
                            $scope.Pager.startId,
                            $scope.Pager.pageIndex,
                            $scope.time)
                        .then(function (response) {
                            $scope.buildBlogs(response);
                        });
                }

            }

            /**
             * 根据userid获取微博列表数据
             * @returns {} 
             */
            $scope.getTraderBlogList = function () {
                var traderId = $('.weibo_wrap').attr('blog-user');
                microblogsService.getTraderBlogList(traderId, $scope.Pager.startId, $scope.Pager.pageIndex)
                    .then(function (response) {
                        $scope.buildBlogs(response);
                    });

            }


            /**
             * 初始化获取列表的准备工作
             * @returns {boolean} 
             */
            $scope.initPending = function () {

                var flag = ($(document).scrollTop() + $(window).height() == $(document).height());
                if ($scope.isOpen) {
                    if (!flag) {
                        return false;
                    }
                }

                if ($scope.busy) {
                    return false;
                }
                if ($scope.Pager.pageIndex > $scope.Pager.TotalPages) {
                    return false;
                }
                $scope.Pager.pageIndex += 1;
                $scope.busy = true;
                return true;
            }

            /**
             * 构建微博结果
             * @param {} response 
             * @returns {} 
             */
            $scope.buildBlogs = function (response) {
                var dataList = response.data.list.Items;
                $scope.Pager.TotalPages = response.data.list.TotalPages;
                if (!dataList) return;
                dataList = dataList.filter(function (item) {
                    return item.MicroBlog.ModelStatus != 3 && item.MicroBlog.ModelStatus != 4;
                });
                if (dataList.length > 0) {
                    $scope.Pager.startId = dataList[dataList.length - 1].MicroBlog.Id;
                    $scope.isOpen = true;
                } else {
                    $scope.isOpen = false;
                    $scope.busy = false;
                }

                /* add for trade dynamic --by albert */
                var clone = function (obj) {
                    return JSON.parse(JSON.stringify(obj));
                }
                var dynamicparse = function (s) {
                    try {
                        var obj = JSON.parse(s);
                        return obj;
                    } catch (error) {
                        return null;
                    }
                }
                var dynamicformat = function (obj) {
                    if (!obj || !obj.TradeId) return '';
                    var str = '<a href="/social/symbol/';
                    str += obj.SymbolName.replace('/', '');
                    str += '" target="_blank" class="dy-symbol" style="color:#ff6200;font-weight:bold;">$';
                    str += obj.SymbolName;
                    str += '$</a>&nbsp;';
                    str += obj.TradeType == 1 ? '卖出' : '买入';
                    str += '<span class="dy-bold">';
                    str += obj.Volumn;
                    str += '</span>标准手，<span>';
                    str += obj.OpenPrice + '→' + obj.ClosePrice;
                    str += '</span>，获利&nbsp;<span class="dy-profit" style="color:#096;font-weight:bold;">$' + obj.Profit + '</span>';
                    // str += obj.FollowerInfos;
                    // 交易员显示跟随
                    if (obj.FollowerInfos) {
                        str += '，' + obj.Followers + '人跟随获利&nbsp;<span class="dy-bold" style="font-weight:bold;">$' + obj.FollowersTotalProfit + '</span>';
                    }
                    return str;
                }

                for (var i = 0; i < dataList.length; i++) {
                    var obj = dynamicparse(dataList[i].MicroBlog.BlogBody);
                    if (obj && obj.TradeId) {
                        var tmp = clone(dataList[i]);
                        tmp.MicroBlog.BlogBody = dynamicformat(obj);
                        if (obj.ImgUrl) {
                            tmp.ImgUrlList = [obj.ImgUrl];
                        }
                        $scope.Pager.itemList.push(tmp);
                    } else {
                        $scope.Pager.itemList.push(dataList[i]);
                    }
                }
                $scope.busy = false;
                window.setInterval(function () {
                    $(".imgList").slideImg();
                }, 1000)
            }

            /**
             * 获取我的关注列表
             * @returns {} 
             */
            $scope.getFollowList = function () {
                var res = $scope.initPending();
                if (!res) return;
                microblogsService.getFollowerList($scope.Pager.pageIndex, -1).then(function (response) {
                    var dataList = response.data.list.Items;
                    $scope.Pager.TotalPages = response.data.list.TotalPages;
                    if (!dataList) return;
                    if (dataList.length > 0) {
                        $scope.isOpen = true;
                    } else {
                        $scope.isOpen = false;
                        $scope.busy = false;
                    }
                    for (var i = 0; i < dataList.length; i++) {
                        $scope.Pager.itemList.push(dataList[i]);
                    }
                    $scope.busy = false;
                })

            }


            /**
             * 获取粉丝列表
             * @returns {} 
             */
            $scope.getBeFolloweredList = function () {
                var res = $scope.initPending();
                if (!res) return;
                microblogsService.getBeFolloweredList($scope.Pager.pageIndex).then(function (response) {
                    var dataList = response.data.list.Items;
                    $scope.Pager.TotalPages = response.data.list.TotalPages;
                    if (!dataList) return;
                    if (dataList.length > 0) {
                        $scope.isOpen = true;
                    } else {
                        $scope.isOpen = false;
                        $scope.busy = false;
                    }
                    for (var i = 0; i < dataList.length; i++) {
                        $scope.Pager.itemList.push(dataList[i]);
                    }
                    $scope.busy = false;
                })

            }



            /**
             * 加载长微博数据
             * @param {Number} 24小时 or 48小时 
             * @returns {} 
             */
            $scope.loadBlogData = function (time) {
                if (!time) {
                    time = 24; //默认24
                }
                $scope.time = time;
                $scope.Pager.itemList = [];
                $scope.Pager.pageIndex = 0;
                $scope.Pager.startId = 0;
                $scope.isOpen = false;
                $scope.busy = false;
                $scope.goMicroBlogs();

            }

            //重新加载热门微博数据
            $rootScope.$on('BLOG_LIST_RELOAD', function () {
                console.log('重新加载热门微博数据。。。')
                $scope.loadBlogData();
            })

            /**
             * 发布微博
             * @returns {} 
             */
            $scope.submitBlog = function () {
                var imgIds = $scope.File.getImgIds(); //文件列表
                var body = $scope.BlogContent;
                if ($scope.isSend == false) {
                    return;
                }
                if ((body != null && body != "" && HtmlUtil.textTrim(body) != "" && HtmlUtil.textTrim(body) != null) || (imgIds != null && imgIds != "")) {
                    $scope.isSend = false;
                    body = HtmlUtil.htmlEncode(body + new String(' '));
                    microblogsService.reportMicroBlog(body, imgIds, function (data) {
                        $scope.isSend = true;
                        if (data != null) {
                            if (data.error != null) {
                                msg(data.error, 1);

                            } else if (data.list.length > 0) {
                                $scope.BlogContent = "";
                                $scope.resetImg();
                                msg("发布成功");
                                if (window.location.pathname.indexOf("/social/blogs") > -1) {
                                    window.location.href = '/social'
                                } else {
                                    //刷新列表
                                    $rootScope.$emit('BLOG_LIST_RELOAD')
                                }


                            }
                        }
                    })
                } else {
                    msg("请输入有效内容", 1);
                }
            }

            $(".eBlog").qqFace({
                id: 'facebox', //表情盒子的ID
                assign: '', //给那个控件赋值
                path: 'face/' //表情存放的路径
            });

            /**
             * 点击发送私信
             * @param {} $index 
             * @returns {} 
             */
            $scope.ShowPrivateLetterDlg = function ($index) {
                requiredLogin(function () {
                    var userId, displayName;
                    var item = $scope.Pager.itemList[$index] || $scope.Pager.itemList[$index];
                    userId = item.MicroBlog ? item.MicroBlog.UserId : item.Id;
                    displayName = item.MicroBlog ? item.MicroBlog.UserDisplayName : item.NickName;
                    $scope.$emit('SHOW_LETTER_DIALOG', userId, displayName);
                })

            }

            /**
             * 普通的发送私信窗口
             * @param {} uid 
             * @param {} name 
             * @returns {} 
             */
            $scope.ShowPrivateLetter = function (uid, name) {
                requiredLogin(function () {
                    $scope.$emit('SHOW_LETTER_DIALOG', uid, name);
                })


            }


            /**
             * 关注或取消关注
             * @param {$index}  
             * @returns {} 
             */
            $scope.AttentionUser = function ($index) {
                blogType = $('.weibo_wrap').attr('blog-type');
                var item = $scope.Pager.itemList[$index];
                var uid = item.MicroBlog ? item.MicroBlog.UserId : item.Id;
                var Func = function () {
                    microblogsService.AttentionUser(uid, function (data) {
                        if (data != null && data) {
                            if (item.MicroBlog) { //普通的微博列表
                                for (var i = 0; i < $scope.Pager.itemList.length; i++) {
                                    var cUid = $scope.Pager.itemList[i].MicroBlog.UserId;
                                    if (cUid == uid) {
                                        $scope.Pager.itemList[i].IsAttention = !$scope.Pager.itemList[i].IsAttention;
                                    }
                                }
                            } else { //其他列表的情况
                                if (item.IsAttention) { //取消关注
                                    var text = $("#MyAttention_Menu").text();
                                    var match = text.match(/\d+/);
                                    if (match) {
                                        var newNum = parseInt(match[0]) - 1;
                                        $("#MyAttention_Menu").text(text.replace(/\d+/, newNum));
                                    }
                                    if (blogType == 4) { //当前是关注列表来的
                                        $scope.Pager.itemList.splice($index, 1);
                                    } else if (blogType == 5) { //粉丝列表来的
                                        item.IsAttention = false; //取消关注
                                    }
                                } else { //添加关注
                                    var text = $("#MyAttention_Menu").text();
                                    var match = text.match(/\d+/);
                                    if (match) {
                                        var newNum = parseInt(match[0]) + 1;
                                        $("#MyAttention_Menu").text(text.replace(/\d+/, newNum));
                                    }
                                    if (blogType == 5) { //粉丝列表来的
                                        item.IsAttention = true; //设置为添加关注
                                    }
                                }



                            }

                            //触发事件
                            getUserAssociate();
                        }
                    });
                }

                if (item.IsAttention == true) {
                    confirmBox('确定要取消关注吗?', function () {
                        Func();
                    }, uid);
                } else {
                    Func();
                }

            }


            //发布微博，评论，回复，各个小功能框点击的显示和隐藏
            $rootScope.showFollerUserDlg = function (e) {
                var inputId, divId;
                if (!$(e.target).attr('input-id')) { //当前子元素没有，去父元素找
                    inputId = $(e.target).parent().attr('input-id');
                    divId = $(e.target).parent().attr('div-id');
                } else {
                    inputId = $(e.target).attr('input-id');
                    divId = $(e.target).attr('div-id');
                }

                //滚动条
                //var nicesx = $(".nui-scroll").niceScroll({ touchbehavior: false, cursorcolor: "#a3a6af", cursoropacitymax: 0.6, cursorwidth: 8, horizrailenabled: false });
                requiredLogin(function () {
                    if ($("#" + divId).is(":hidden")) { //显示的时候加载
                        $rootScope.loadFollowers(e)
                    }
                    $("#" + divId).find('input').val('');
                    $("#" + divId).toggle();
                })


            }


            //加载好友（搜索的时候直接用）
            $rootScope.loadFollowers = function (e) {
                var inputId, divId, key;
                if (!$(e.target).attr('input-id')) { //当前子元素没有，去父元素找
                    inputId = $(e.target).parent().attr('input-id');
                    divId = $(e.target).parent().attr('div-id');
                    key = $(e.target).parent().val();
                } else {
                    inputId = $(e.target).attr('input-id');
                    divId = $(e.target).attr('div-id');
                    key = $(e.target).val();
                }

                microblogsService.getFollowers(key, function (data) {
                    $("#" + divId).find('ul').empty();
                    if (data != null && data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var o = data[i];
                            var html = $('<li style="padding-left:10px;">' + o + '</li>');
                            html.click(function (event) {
                                aiTeUser(inputId, divId, $(event.target));
                            });
                            $("#" + divId).find('ul').append(html);
                        }
                    }
                })
            }


            var scroll_pos = 0;

            //微博展开
            $scope.btnToShow = function (id, oid) {
                if ($.trim($("#BlogBody_" + id).html()) == "" || $("#BlogBody_" + id).html() == null) {
                    var blogId = oid == 0 ? id : oid;
                    microblogsService.getLongBlogBodyById(blogId, function (data) {
                        if (data != null && data !== "") {
                            $("#BlogBody_" + id).html(data);
                        }
                    });

                }
                scroll_pos = $(document).scrollTop();
                var _this = $("#js_readallbtn_" + id);
                _this.parents('.cwb_mediasmallBox').hide();
                _this.parents('.cwb_mediasmallBox').siblings('.cwb_detailbox_wrap').show();

                //更新微博阅读数量
                microblogsService.updateBlogViewCount(id,
                    function (res) {
                        console.log(res)
                    });

            }

            //微博收起
            $scope.btnToHide = function (id) {
                $(document).scrollTop(scroll_pos);
                var _this = $(".js-showqi_" + id);
                _this.parents('.cwb_detailbox_wrap').hide();
                _this.parents('.cwb_detailbox_wrap').siblings('.cwb_mediasmallBox').show();
            }



            $(document).on('click', '.imgList', function () {
                //图片浏览插件


                $(".imgList").slideImg();
            })


        })
        .config([
            '$compileProvider',
            function ($compileProvider) {
                $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|javascript):/);
            }
        ]).filter('to_trusted', [
            '$sce',
            function ($sce) {
                return function (text) {
                    return $sce.trustAsHtml(text);
                };
            }
        ]);


}());